//
//  VideoViewController.m
//  Project_B
//
//  Created by dllo on 15/12/22.
//  Copyright © 2015年 ZY. All rights reserved.
//

#import "VideoViewController.h"
#import <Masonry.h>
#import "VideoReusableView.h"
#import "VideoCollectionViewCell.h"
#import "VideoHeaderDetailViewController.h"
#import "LJDTools.h"
#import "VideoHeaderModel.h"
#import "VideoModel.h"

#pragma mark - 4.delegate：签订协议
@interface VideoViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, tapActionDelegate>

@property (nonatomic, strong)UICollectionView *collectionView;
// 头视图数组
@property (nonatomic, strong)NSMutableArray *headerArray;
// 视频数组
@property (nonatomic, strong)NSMutableArray *videoArray;
// 判断上拉还是下拉
@property (nonatomic, assign)BOOL isUpDown;
// 页码
@property (nonatomic, assign)NSInteger page;

@end

@implementation VideoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.view.backgroundColor = [UIColor whiteColor];
    // 设置导航栏不透明
    self.navigationController.navigationBar.translucent = NO;
    
    self.navigationItem.title = @"视听";
    
    
#pragma mark - 创建collectionView
    [self createCollectionView];
    
    
    
#pragma mark - 上拉刷新
    // 设置初始页为0
    self.page = 0;
    // 下拉刷新
    [self headerRefresh];
    // 进界面就开始刷新一次
    [self.collectionView.mj_header beginRefreshing];
    
    
#pragma mark - 下拉刷新
    [self footerRefresh];
    
    
#pragma mark - 初始化
    self.headerArray = [NSMutableArray array];
    self.videoArray = [NSMutableArray array];
    
    
 
}



#pragma mark - 下拉刷新
- (void)headerRefresh
{
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 删除数组（下拉一次删除一次）
        [self.headerArray removeAllObjects];
        [self.videoArray removeAllObjects];
        // 从第一页开始
        self.page = 0;
        // 判断是上拉还是下拉
        self.isUpDown = YES;
        // 请求数据
        [self getData];
        // 刷新界面
        [self.collectionView reloadData];
        // 结束刷新
        [self.collectionView.mj_header endRefreshing];
    }];
    
    
}




#pragma mark - 上拉加载
- (void)footerRefresh
{
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        // 每上拉一次，刷新下一页数据（因为数据中10个为一组，所以+10）
        self.page += 10;
        // 判断是上拉还是下拉
        self.isUpDown = NO;
        // 请求数据
        [self getData];
        // 刷新界面
        [self.collectionView reloadData];
        // 结束刷新
        [self.collectionView.mj_footer endRefreshing];
    }];
    
}





#pragma mark - 创建collectionView
- (void)createCollectionView
{
    // 布局
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    // item尺寸
    flowLayout.itemSize = CGSizeMake(SCREEN_WIDTH - 10, 330);
    // 头视图尺寸
    flowLayout.headerReferenceSize = CGSizeMake(SCREEN_WIDTH, 120);
    
    
    // collectionView
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:flowLayout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collectionView];
    // masonry
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.top.mas_equalTo(0);
        make.width.mas_equalTo(SCREEN_WIDTH);
        make.bottom.mas_equalTo(- 49);
        
    }];
    
    
    // 注册cell
    [self.collectionView registerClass:[VideoCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    // 注册头视图
    [self.collectionView registerClass:[VideoReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    
    
    
}



#pragma mark - 请求数据
- (void)getData
{
    
#pragma mark - 视频数据
    [LJDTools getUrl:[NSString stringWithFormat:@"http://c.m.163.com/nc/video/home/%ld-10.html", self.page] body:nil result:LJDJSON headerFile:nil success:^(id result) {
        
        NSMutableArray *array = [result objectForKey:@"videoList"];
        for (NSMutableDictionary *dic in array) {
            VideoModel *videoModel = [VideoModel modelWithDictionary:dic];
            [self.videoArray addObject:videoModel];
            
        }
        // 刷新
        [self.collectionView reloadData];
        
        
    } failure:^(NSError *error) {
        
        /* 请求失败弹出提示框 */
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"网络环境较差,请稍后重试" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alert animated:YES completion:^{
            
        }];
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alert addAction:alertAction];
        
    }];
    
    
    
    
    
#pragma mark - 头视图数据
    [LJDTools getUrl:@"http://c.m.163.com/nc/video/home/0-10.html" body:nil result:LJDJSON headerFile:nil success:^(id result) {
        
        NSMutableArray *array = [result objectForKey:@"videoSidList"];
        for (NSMutableDictionary *dic in array) {
            VideoHeaderModel *videoHeaderModel = [VideoHeaderModel modelWithDictionary:dic];
            [self.headerArray addObject:videoHeaderModel];
        }
        // 刷新
        [self.collectionView reloadData];
        
        
    } failure:^(NSError *error) {
        
        /* 请求失败弹出提示框 */
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"网络环境较差,请稍后重试" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alert animated:YES completion:^{
            
        }];
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alert addAction:alertAction];
        
    }];
    
    
}







#pragma mark - item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    // 判断有数据的时候返回
    if (self.headerArray.count != 0) {
        return self.videoArray.count;
        
    } else {
        return 0;
    }
    
}





#pragma mark - cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *Identifier = @"cell";
    VideoCollectionViewCell *videoCell = [collectionView dequeueReusableCellWithReuseIdentifier:Identifier forIndexPath:indexPath];
    videoCell.backgroundColor = [UIColor whiteColor];
    // 赋值
    videoCell.videoModel = [self.videoArray objectAtIndex:indexPath.row];
    return videoCell;
    
}




#pragma mark - 头视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionHeader) {
        VideoReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
        // 传值（判断有数据在赋值）
        if (_headerArray.count != 0) {
            headerView.videoHeaderModel = [self.headerArray objectAtIndex:indexPath.row];
            // 存到数组里，方便循环取值
            headerView.headerArray = self.headerArray;
        }
        
#pragma mark - 5.delegate：设置代理人
        headerView.tapDelegate = self;
//        [headerView removeFromSuperview];
        return headerView;
        
    }
    return nil;
}






#pragma mark - 6.delegate：实现协议方法
- (void)presentViewToViewController:(NSInteger)tag
{
    VideoHeaderDetailViewController *videoHeaderDetailVC = [[VideoHeaderDetailViewController alloc] init];
    // 点进去是哪个View(取出点击的model)
    VideoHeaderModel *videoHeaderModel = [self.headerArray objectAtIndex:tag - 100];
    videoHeaderDetailVC.sid = videoHeaderModel.sid;
    // push
    [self.navigationController pushViewController:videoHeaderDetailVC animated:YES];
}











- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
